<template>
  <PageContainer
    title="车辆管理"
    :actions="pageActions"
    :columns="columns"
    :data-source="vehicleList"
    :loading="loading"
    :pagination-data="pagination"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <a-form-item label="车辆状态">
        <a-select
          v-model:value="queryParams.vehicleStatus"
          placeholder="全部状态"
          style="width: 150px"
          allowClear
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option
            v-for="option in statusOptions"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="关键词">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="车牌号、品牌型号"
          style="width: 200px"
          allowClear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <!-- 车牌号 -->
      <template v-if="column.key === 'plateNumber'">
        <a class="plate-link" @click="handleView(record)">{{
          record.plateNumber
        }}</a>
      </template>

      <!-- 车辆类型 -->
      <template v-else-if="column.key === 'vehicleType'">
        <a-tag color="blue">
          {{ getVehicleTypeLabel(record.vehicleType) }}
        </a-tag>
      </template>

      <!-- 车辆来源 -->
      <template v-else-if="column.key === 'vehicleSource'">
        <a-tag :color="record.vehicleSource === 'TEMP' ? 'orange' : 'green'">
          {{ record.vehicleSource === "TEMP" ? "临时车" : "公司车" }}
        </a-tag>
      </template>

      <!-- 载重/容积 -->
      <template v-else-if="column.key === 'capacity'">
        <div>{{ record.loadCapacity }}吨</div>
        <div class="capacity-detail">{{ record.volumeCapacity || "-" }}m³</div>
      </template>

      <!-- 车主信息 -->
      <template v-else-if="column.key === 'ownerInfo'">
        <div class="owner-info">
          <div class="owner-name">{{ record.ownerName || "-" }}</div>
          <div class="owner-phone">{{ record.ownerPhone || "-" }}</div>
        </div>
      </template>

      <!-- 车辆状态 -->
      <template v-else-if="column.key === 'vehicleStatus'">
        <a-tag :color="getStatusColor(record.vehicleStatus)">
          {{ getVehicleStatusLabel(record.vehicleStatus) }}
        </a-tag>
      </template>

      <!-- 证件到期 -->
      <template v-else-if="column.key === 'expireInfo'">
        <div :class="getExpireClass(record.insuranceExpireDate)">
          保险：{{ formatDate(record.insuranceExpireDate) }}
        </div>
        <div :class="getExpireClass(record.inspectionExpireDate)">
          年检：{{ formatDate(record.inspectionExpireDate) }}
        </div>
      </template>

      <!-- 操作 -->
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button type="link" size="small" @click="handleView(record)">
            查看
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleEdit(record)"
            v-permission="($route?.meta as any)?.$actions?.['edit']?.code"
          >
            编辑
          </a-button>
          <a-button type="link" size="small" @click="handleViewOrders(record)">
            查看订单
          </a-button>
          <a-popconfirm
            title="确定删除该车辆吗？"
            @confirm="handleDelete(record)"
            v-permission="($route?.meta as any)?.$actions?.['delete']?.code"
          >
            <a-button type="link" size="small" danger> 删除 </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined, ExportOutlined } from "@ant-design/icons-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import { getVehicleList, deleteVehicle } from "@/api/tenant/vehicle";
import type { Vehicle } from "@/types/vehicle";
import { formatDate } from "@/utils/format";
import { useDictionary } from "@/composables/useDictionary";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute();

// 字典
const { getLabel: getVehicleTypeLabel, loadDictionaries: loadVehicleTypes } =
  useDictionary("VEHICLE_TYPE");
const {
  getLabel: getVehicleStatusLabel,
  loadDictionaries: loadVehicleStatuses,
  options: statusOptions,
} = useDictionary("VEHICLE_STATUS");

const queryParams = reactive({
  current: 1,
  size: 10,
  vehicleStatus: "",
  keyword: "",
});

const vehicleList = ref<Vehicle[]>([]);
const loading = ref(false);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ["10", "20", "50", "100"],
});

// 页面操作按钮配置
const pageActions = computed(() => [
  {
    key: "create",
    label: "新增车辆",
    type: "primary" as const,
    icon: PlusOutlined,
    permission: (route.meta as any)?.$actions?.create?.code,
    onClick: handleCreate,
  },
  {
    key: "export",
    label: "导出",
    icon: ExportOutlined,
    onClick: () => {
      message.info("导出功能开发中");
    },
  },
]);

// 表格列配置
const columns = [
  { title: "车牌号", dataIndex: "plateNumber", key: "plateNumber", width: 100 },
  { title: "车辆类型", key: "vehicleType", width: 120 },
  { title: "来源", key: "vehicleSource", width: 100 },
  { title: "品牌型号", dataIndex: "brandModel", key: "brandModel", width: 150 },
  { title: "载重/容积", key: "capacity", width: 120 },
  { title: "车主信息", key: "ownerInfo", width: 180 },
  { title: "车辆状态", key: "vehicleStatus", width: 100 },
  { title: "证件到期", key: "expireInfo", width: 150 },
  {
    title: "操作",
    key: "action",
    fixed: "right" as const,
    width: 260,
    align: "center" as const,
  },
];

// 获取车辆列表
const fetchVehicleList = async () => {
  loading.value = true;
  try {
    const response = await getVehicleList({
      ...queryParams,
      current: pagination.current,
      size: pagination.pageSize,
    });

    const data = response.data as any;
    vehicleList.value = data.records || [];
    pagination.total = data.total || 0;
  } catch (error: any) {
    console.error("获取车辆列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchVehicleList();
};

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    vehicleStatus: "",
    keyword: "",
  });
  pagination.current = 1;
  fetchVehicleList();
};

// 分页变化
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchVehicleList();
};

// 新增车辆
const handleCreate = () => {
  router.push("/tenant/vehicle/create");
};

// 查看详情
const handleView = (record: Vehicle) => {
  router.push(`/tenant/vehicle/${record.id}`);
};

// 编辑车辆
const handleEdit = (record: Vehicle) => {
  router.push(`/tenant/vehicle/edit/${record.id}`);
};

// 查看车辆订单
const handleViewOrders = (record: Vehicle) => {
  router.push({
    path: "/tenant/order",
    state: {
      vehicleId: record.id,
      vehiclePlateNumber: record.plateNumber,
      fromNavigation: true, // 标记是从导航跳转而来
    },
  });
};

// 删除车辆
const handleDelete = (record: Vehicle) => {
  Modal.confirm({
    title: "删除车辆",
    content: `确定要删除车辆 ${record.plateNumber} 吗？`,
    okText: "确定删除",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await deleteVehicle(record.id);
        message.success("车辆删除成功");
        fetchVehicleList();
      } catch (error: any) {
        console.error("删除车辆失败:", error);
        if (error.message && error.message !== "Error") {
          message.error(error.message);
        }
      }
    },
  });
};

// 判断证件是否即将到期
const getExpireClass = (date: string) => {
  const daysLeft = dayjs(date).diff(dayjs(), "day");
  if (daysLeft < 0) return "expire-overdue";
  if (daysLeft <= 30) return "expire-warning";
  return "expire-normal";
};

// 初始化
// 获取状态颜色 - 只包含系统定义的3种核心状态
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    AVAILABLE: "green", // 空闲 - 绿色
    IN_USE: "blue", // 运输中 - 蓝色
    MAINTENANCE: "orange", // 维修中 - 橙色
  };
  return colorMap[status] || "default";
};

onMounted(() => {
  // 清除字典缓存以确保获取最新数据
  import("@/composables/useDictionary").then(({ clearDictionaryCache }) => {
    clearDictionaryCache("VEHICLE_STATUS");
    clearDictionaryCache("VEHICLE_TYPE");
  });

  loadVehicleTypes();
  loadVehicleStatuses();
  fetchVehicleList();
});
</script>

<style scoped>
/* 自定义样式 */

/* 车牌号链接 */
.plate-link {
  color: var(--primary-color);
  font-weight: 600;
  font-family: monospace;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.plate-link:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

/* 容积详情 */
.capacity-detail {
  color: var(--text-secondary);
  font-size: 12px;
  margin-top: 2px;
}

/* 车主信息 */
.owner-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.owner-name {
  font-weight: 500;
  color: var(--text-primary);
}

.owner-phone {
  color: var(--text-secondary);
  font-size: 12px;
}

/* 证件到期状态 */
.expire-normal {
  color: var(--text-secondary);
  font-size: 13px;
}

.expire-warning {
  color: var(--warning-color);
  font-size: 13px;
  font-weight: 500;
}

.expire-overdue {
  color: var(--error-color);
  font-size: 13px;
  font-weight: 500;
}
</style>
